package com.yms.jvm.invokedynamic;

import java.lang.invoke.*;

import static java.lang.invoke.MethodHandles.lookup;

/**
 * @version : 1.0
 * @author: yangmingsong
 * @date: 2022/7/16-07-16-15:40
 * @description: spring5Test 动态语言指令测试 模拟InvokeDynamic指令
 */
public class Test {
    public static void main(String[] args) throws Throwable {
        INDY_BootstrapMethod().invokeExact("icyfenix");
    }

    private static void testMethod(String s){
        System.out.println(s);
    }

    private static MethodHandle INDY_BootstrapMethod() throws Throwable {

        CallSite callSite = (CallSite) MH_BootstrapMethod().invokeWithArguments(lookup(),
                "testMethod", MethodType.fromMethodDescriptorString("(Ljava/lang/String;)V",null)
                );
        return callSite.dynamicInvoker();
    }

    private static MethodType MT_BootstrapMethod() {
        return MethodType.fromMethodDescriptorString("(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;" +
                "Ljava/lang/invoke/MethodType;)Ljava/lang/invoke/CallSite;",null);
    }
    private static MethodHandle MH_BootstrapMethod() throws NoSuchMethodException, IllegalAccessException {
        return lookup().findStatic(Test.class,"BootstrapMethod",MT_BootstrapMethod());
    }

    private static CallSite BootstrapMethod(MethodHandles.Lookup lookup,String s,MethodType methodType) throws NoSuchMethodException, IllegalAccessException {
        return new ConstantCallSite(lookup.findStatic(Test.class,s,methodType));
    }

}
